from django.contrib.auth.decorators import login_required
from django.core.handlers.wsgi import WSGIRequest
from django.http import Http404
from django.shortcuts import render
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework import status
from rest_framework.response import Response
from apps.mlplatform.models.task import VisualRecognitionTask
from .models.task import Task
from apps.storage.utils.general import general_response_data
from .client import MLPMJobsClient
from django.conf import settings
import json
import os

client_job = MLPMJobsClient(settings.MLPM_USERNAME, settings.MLPM_PASSWORD, settings.MLPM_JOB_SERVER)


# Create your views here.

def get_task_result(task_id):
    resp = client_job.result(task_id)
    if json.loads(resp.content)['code'] == 0:
        print(resp.content)
        return json.loads(resp.content)['data']['result']['result']
    else:
        return {'error': json.loads(resp.content)['msg']}


def save_result_file(filename):
    resp = client_job.get_file(filename)
    if resp.status_code == 200:
        file = os.path.join('results', filename)
        with open(os.path.join(settings.MEDIA_ROOT, file), 'wb') as f:
            for chunk in resp.iter_content(100000):
                f.write(chunk)
        return file
    return None


class FormatListCreateAPIView(ListCreateAPIView):
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        data = general_response_data(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         data = general_response_data(serializer.data)
    #         return self.get_paginated_response(data)
    #
    #     serializer = self.get_serializer(queryset, many=True)
    #     data = general_response_data(serializer.data)
    #     return Response(data)


class FormatRetrivevAPIView(RetrieveUpdateDestroyAPIView):
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = general_response_data(serializer.data)
        return Response(data)

    def delete(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        data = general_response_data({})
        return Response(data, status=status.HTTP_204_NO_CONTENT)


@login_required
def index(req):
    '''
    :param req:请求
    :return: 模板
    '''
    return render(req, template_name='mlplatform/index.html')


def test(req):
    '''
    :param req:请求
    :return: 模板
    '''
    return render(req, template_name='mlplatform/test.html')


@login_required
def my_tasks(req: WSGIRequest):
    tasks = Task.objects.filter(author=req.user.username)
    for task in tasks:
        if not task.status == 2 and task.task_id:
            try:
                task.result = get_task_result(task.task_id)
                task.result_file = save_result_file(task.result['filename'])
                task.status = 2
                if 'error' in task.result.keys():
                    task.status = 3
                task.save()
            except Exception as e:
                pass
    return render(req, template_name='mlplatform/my_tasks.html')


@login_required
def my_vrtasks(req: WSGIRequest):
    # tasks = Task.objects.filter(author=req.user.username)
    # for task in tasks:
    #     if not task.status == 2 and task.task_id:
    #         task.result = get_task_result(task.task_id)
    #         task.status = 2
    #         if 'error' in task.result.keys():
    #             task.status = 3
    #         task.save()
    return render(req, template_name='mlplatform/my_vrtasks.html')


def view_task(req: WSGIRequest, tid):
    try:
        task = Task.objects.get(id=tid)
        context = dict(meta=task)
        return render(req, 'mlplatform/view_task.html', context=context)
    except Task.DoesNotExist:
        raise Http404


def view_vrtask(req: WSGIRequest, tid):
    try:
        # vrtask = VisualRecognitionTask.objects.get(id=tid)
        # context = dict(meta=vrtask)
        # return render(req, 'mlplatform/view_task.html', context=context)
        return render(req, 'mlplatform/view_vrtask.html')
    except Task.DoesNotExist:
        raise Http404
